<template>
  <div class="workshop-page">
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Setting /></el-icon>
          <span>产能管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><Menu /></el-icon>
          <span>车间管理</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" class="filter-form" inline @keyup.enter="handleSearch">
        <el-form-item>
          <el-input v-model="searchForm.workshopnameorcode" placeholder="请输入车间编号/名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.personText" placeholder="请输入负责人" clearable />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable class="w-180">
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="2" />
          </el-select>
        </el-form-item>
        <div class="filter-actions">
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <div class="toolbar">
        <el-button type="primary" @click="openWorkshopDialog">新增</el-button>
        <el-button type="danger" plain :disabled="!multipleSelection.length" @click="batchDelete">删除</el-button>
      </div>

      <el-table
        :data="pagedRows"
        border
        stripe
        :loading="loading"
        class="workshop-table"
        height="640"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="48" />
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="workshopcode" label="车间编号" min-width="140" />
        <el-table-column prop="workshopname" label="车间名称" min-width="160" />
        <el-table-column prop="workshoparea" label="车间面积" min-width="120" align="right" />
        <el-table-column prop="workshoppersonid" label="负责人" min-width="120" />
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">{{ scope.row.status === 1 ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="bz" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="openEditDialog(scope.row)">编辑</el-button>
            <el-divider direction="vertical" />
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-12 flex-end">
        <el-pagination
          v-model:current-page="pager.page"
          v-model:page-size="pager.size"
          :page-sizes="[1, 2, 3, 4]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pager.total"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="workshopDialog.visible"
      :title="workshopDialog.mode === 'create' ? '新增车间' : '编辑车间'"
      width="640px"
      :close-on-click-modal="false"
      @closed="resetWorkshopForm"
    >
      <el-form ref="workshopFormRef" :model="workshopForm" :rules="workshopRules" label-width="120px" class="detail-form">
        <div class="two-col">
          <el-form-item label="车间编号" prop="workshopcode">
            <div class="code-field">
              <el-input v-model="workshopForm.workshopcode" placeholder="请输入车间编号" :disabled="workshopForm.autoCode" />
              <el-switch v-model="workshopForm.autoCode" inline-prompt active-text="系统编号" inactive-text="系统编号" @change="onAutoCodeToggle" />
            </div>
          </el-form-item>
          <el-form-item label="车间名称" prop="workshopname">
            <el-input v-model="workshopForm.workshopname" placeholder="请输入车间名称" />
          </el-form-item>
          <el-form-item label="车间面积" prop="workshoparea">
            <el-input-number v-model="workshopForm.workshoparea" :min="0" :step="10" class="w-full" placeholder="请输入车间面积" />
          </el-form-item>
          <el-form-item label="负责人ID" prop="workshoppersonid">
            <el-input-number v-model="workshopForm.workshoppersonid" :min="0" :step="1" class="w-full" placeholder="请输入负责人ID" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="workshopForm.status">
              <el-radio-button :label="1">启用</el-radio-button>
              <el-radio-button :label="2">停用</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </div>
        <el-form-item label="备注">
          <el-input v-model="workshopForm.bz" type="textarea" :rows="4" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="workshopDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="workshopDialog.loading" @click="handleWorkshopSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import https from '@/Http/http'
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { ArrowRight, HomeFilled, Setting, Menu } from '@element-plus/icons-vue'
import { extractPayload, getErrorMessage, getResponseMessage, isRequestSuccess } from '@/utils/responseHelper'

interface WorkshopItem {
  id: number
  workshopcode: string
  workshopname: string
  workshoparea: number
  workshoppersonid: number
  status: number
  bz: string
}

// 使用统一的https.Reads路由

const loading = ref(false)
const rows = ref<WorkshopItem[]>([])
const multipleSelection = ref<WorkshopItem[]>([])

const pager = reactive({ page: 1, size: 10, total: 0 })
const pagedRows = computed(() => rows.value)

const searchForm = reactive({
  workshopnameorcode: '',
  personText: '',
  status: undefined as number | undefined,
})

const workshopFormRef = ref<FormInstance>()
const workshopDialog = reactive({ visible: false, loading: false, mode: 'create' as 'create' | 'edit' })
const workshopForm = reactive({
  id: undefined as number | undefined,
  workshopcode: '',
  workshopname: '',
  workshoparea: undefined as number | undefined,
  workshoppersonid: undefined as number | undefined,
  status: 1,
  bz: '',
  autoCode: true,
})

const workshopRules = reactive<FormRules>({
  workshopcode: [{ required: true, message: '请输入车间编号', trigger: 'blur' }],
  workshopname: [{ required: true, message: '请输入车间名称', trigger: 'blur' }],
  workshoparea: [{ required: true, message: '请输入车间面积', trigger: 'change' }],
  workshoppersonid: [{ required: true, message: '请输入负责人ID', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
})

const generateCode = () => {
  const now = new Date()
  const p = (n: number) => `${n}`.padStart(2, '0')
  return `CJ${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}${p(now.getHours())}${p(now.getMinutes())}${p(now.getSeconds())}`
}
const onAutoCodeToggle = () => { if (workshopForm.autoCode) workshopForm.workshopcode = generateCode() }

const fetchList = async () => {
  loading.value = true
  try {
    const response = await https.Reads.get(`/ADeviceManagement/AWorkshopShow`, { params: {
      workshopnameorcode: searchForm.workshopnameorcode || undefined,
      status: searchForm.status ?? 0,
      PageIndex: pager.page,
      PageSize: pager.size,
    } })
    const payload = extractPayload(response)
    if (!isRequestSuccess(payload) && !Array.isArray(payload?.data ?? payload?.Data)) {
      throw new Error(getResponseMessage(payload, '获取车间列表失败'))
    }
    const list: WorkshopItem[] = payload?.data ?? payload?.Data ?? []
    const key = searchForm.personText?.trim()
    rows.value = key ? list.filter(x => String(x.workshoppersonid).includes(key)) : list
    pager.total = payload?.totalCount ?? payload?.TotalCount ?? list.length
  } catch (error) {
    ElMessage.error(getErrorMessage(error, '获取车间列表失败'))
  } finally {
    loading.value = false
  }
}

const handleSearch = () => { fetchList() }
const handleReset = () => {
  searchForm.workshopnameorcode = ''
  searchForm.personText = ''
  searchForm.status = undefined
  pager.page = 1
  fetchList()
}

const onSelectionChange = (arr: WorkshopItem[]) => { multipleSelection.value = arr }

const resetWorkshopForm = () => {
  workshopForm.id = undefined
  workshopForm.workshopcode = ''
  workshopForm.workshopname = ''
  workshopForm.workshoparea = undefined
  workshopForm.workshoppersonid = undefined
  workshopForm.status = 1
  workshopForm.bz = ''
  workshopForm.autoCode = true
  workshopFormRef.value?.clearValidate()
  onAutoCodeToggle()
}

const openWorkshopDialog = () => {
  workshopDialog.mode = 'create'
  resetWorkshopForm()
  workshopDialog.visible = true
}
const openEditDialog = (row: WorkshopItem) => {
  workshopDialog.mode = 'edit'
  workshopForm.id = row.id
  workshopForm.workshopcode = row.workshopcode
  workshopForm.workshopname = row.workshopname
  workshopForm.workshoparea = row.workshoparea
  workshopForm.workshoppersonid = row.workshoppersonid
  workshopForm.status = row.status
  workshopForm.bz = row.bz
  workshopForm.autoCode = false
  workshopDialog.visible = true
}

const handleWorkshopSubmit = () => {
  workshopFormRef.value?.validate(async (valid) => {
    if (!valid) return
    if (workshopDialog.mode === 'edit' && !workshopForm.id) {
      ElMessage.error('缺少车间ID')
      return
    }
    workshopDialog.loading = true
    const payload = {
      id: workshopForm.id,
      workshopcode: workshopForm.workshopcode,
      workshopname: workshopForm.workshopname,
      workshoparea: Number(workshopForm.workshoparea ?? 0),
      workshoppersonid: Number(workshopForm.workshoppersonid ?? 0),
      status: workshopForm.status,
      bz: workshopForm.bz,
    }
    try {
      const request = workshopDialog.mode === 'create'
        ? https.Writes.post('/AWorkshop/WorkshopAdd', payload)
        : https.Writes.put('/AWorkshop/WorkshopEdit', payload)
      const response = await request
      const data = extractPayload(response)
      if (isRequestSuccess(data)) {
        ElMessage.success(getResponseMessage(data, workshopDialog.mode === 'create' ? '新增车间成功' : '编辑车间成功'))
        workshopDialog.visible = false
        resetWorkshopForm()
        fetchList()
      } else {
        ElMessage.error(getResponseMessage(data, '保存车间信息失败'))
      }
    } catch (error) {
      ElMessage.error(getErrorMessage(error, workshopDialog.mode === 'create' ? '新增车间失败' : '编辑车间失败'))
    } finally {
      workshopDialog.loading = false
    }
  })
}

const requestDeleteWorkshop = async (id: number) => {
  const response = await https.Writes.delete('/AWorkshop/WorkshopDelete', { params: { id } })
  const data = extractPayload(response)
  if (!isRequestSuccess(data)) {
    throw new Error(getResponseMessage(data, '删除车间失败'))
  }
}

const batchDelete = () => {
  if (!multipleSelection.value.length) return
  ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 条记录吗？`, '提示', { type: 'warning' })
    .then(async () => {
      try {
        await Promise.all(multipleSelection.value.map(item => requestDeleteWorkshop(item.id)))
        ElMessage.success('批量删除成功')
        fetchList()
      } catch (error) {
        ElMessage.error((error as Error).message || '批量删除失败')
      }
    })
    .catch(() => {})
}

const handleDelete = (row: WorkshopItem) => {
  ElMessageBox.confirm(`确认删除「${row.workshopname}」吗？`, '提示', { type: 'warning' })
    .then(async () => {
      try {
        await requestDeleteWorkshop(row.id)
        ElMessage.success('删除成功')
        fetchList()
      } catch (error) {
        ElMessage.error((error as Error).message || '删除失败')
      }
    })
    .catch(() => {})
}

const onPageSizeChange = (size: number) => { pager.size = size; pager.page = 1; fetchList() }
const onPageChange = (page: number) => { pager.page = page; fetchList() }

onMounted(() => { fetchList() })
</script>

<style scoped>
.workshop-page {
  padding: 16px;
  min-height: 100%;
  box-sizing: border-box;
  position: relative;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  background-image:
    url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5z' fill='%23ffffff' fill-opacity='0.03' fill-rule='evenodd'/%3E%3C/svg%3E"),
    linear-gradient(135deg, #667eea15 0%, #764ba215 50%, #f093fb15 100%);
  background-size: 200px 200px, cover;
  background-position: 0 0, center;
  background-attachment: fixed;
}

.workshop-page::before { content: ""; position: fixed; inset: 0; pointer-events: none; z-index: 0; }
.workshop-page > * { position: relative; z-index: 1; }

.breadcrumb-container {
  margin-bottom: 16px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
  position: relative;
  overflow: hidden;
}
.breadcrumb-nav :deep(.el-breadcrumb__inner) { color: rgba(255,255,255,0.9); font-weight: 500; display: inline-flex; align-items: center; gap: 6px; }
.breadcrumb-item.active :deep(.el-breadcrumb__inner) { color: #fff; font-weight: 600; }
.breadcrumb-icon { font-size: 16px; margin-right: 4px; }

.filter-card, .table-card { margin-bottom: 16px; background: rgba(255,255,255,0.95); backdrop-filter: blur(10px); box-shadow: 0 8px 32px rgba(0,0,0,0.08); }
.filter-form { display: flex; align-items: center; gap: 12px; }
.filter-actions { display: flex; gap: 12px; }
.toolbar { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
.workshop-table { width: 100%; }

.detail-form { margin-top: 4px; }
.two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 16px 24px; }
.code-field { display: flex; align-items: center; gap: 12px; }

.mt-12 { margin-top: 12px; }
.w-180 { width: 180px; }
.flex-end { display: flex; justify-content: flex-end; }
</style>
